package org.ziyao.generatezippdf.controller;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.layout.font.FontProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.ziyao.generatezippdf.entity.DeptBean;
import org.ziyao.generatezippdf.entity.OriginBean;
import org.ziyao.generatezippdf.grace.result.GraceJSONResult;
import reactor.core.publisher.Mono;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("report")
public class ReportController {
    
    private final ResourceLoader resourceLoader;


    @GetMapping("create")
    private GraceJSONResult generatePdf() {
        // 创建模板引擎并配置模板解析器
        TemplateEngine templateEngine = new TemplateEngine();
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setPrefix("templates/"); // 模板文件所在目录前缀
        templateResolver.setSuffix(".html"); // 模板文件后缀
        templateResolver.setTemplateMode("HTML");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setOrder(1);
        templateEngine.setTemplateResolver(templateResolver);

        // 假设我们有一个数据集，每个条目都有一个名字
        List<Map<String, Object>> dataItems = new ArrayList<>();

        WebClient client = WebClient.builder()
                .baseUrl("http://dsd.nmgbigdata.com:1002")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
        Mono<OriginBean> mono = client
                .get()  // GET请求
                .uri("/dsd/magic/api/biz/contact_sys/evaluation/evaluation_march/top")   // 请求路径
                .retrieve()   // 获取响应体
                .bodyToMono(OriginBean.class);

        OriginBean originBean = mono.block();
        List<DeptBean> deptBeans = originBean.getData();

        WebClient clientQxq = WebClient.builder()
                .baseUrl("http://dsd.nmgbigdata.com:1002")
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
        Mono<OriginBean> monoQxq = clientQxq
                .get()  // GET请求
                .uri("/dsd/magic/api/biz/contact_sys/evaluation/evaluation_march/top_qxq")   // 请求路径
                .retrieve()   // 获取响应体
                .bodyToMono(OriginBean.class);

        OriginBean originBeanQxq = monoQxq.block();
        deptBeans.addAll(originBeanQxq.getData());

        // 遍历数据集，为每个条目生成PDF
        for (DeptBean deptItem : deptBeans) {
            // 创建上下文并设置变量
            Context context = new Context();
//            context.setVariables(dataItem);
            context.setVariable("name", deptItem.getName()); // 设置name变量的值
            context.setVariable("total", deptItem.getTotal()); // 设置得分
            context.setVariable("imageUrl", "file:///D:/Downloads/" + deptItem.getName() + ".png"); // 设置imageUrl变量的值

            context.setVariable("maxScore", deptItem.getReport().get(0).getValue());
            context.setVariable("averScore", deptItem.getReport().get(1).getValue());
            context.setVariable("selfScore", deptItem.getReport().get(2).getValue());

            context.setVariable("zpSzhqk", deptItem.getZpSzhqk()); // 设置数字化情况
            context.setVariable("zpSjgx", deptItem.getZpSjgx()); // 数据共享及数据分析工作开展情况
            context.setVariable("zpCzwt", deptItem.getZpCzwt()); // 存在的问题
            context.setVariable("xybgzsl", deptItem.getXybgzsl()); // 下一步工作思路

            // 处理模板并获取HTML字符串
            StringWriter writer = new StringWriter();
            templateEngine.process("myTemplate", context, writer);
            String htmlContent = writer.toString();

            // 生成PDF文件名
//            String pdfFileName = "D:\\Project\\generateZipPdf\\" + deptItem.getName()+ ".pdf";
            String pdfFileName = "D:\\generateZipPdf\\" + deptItem.getName()+ ".pdf";

            Path pdfPath = Paths.get(pdfFileName).getParent();
            if (pdfPath != null && !Files.exists(pdfPath)) {
                try {
                    Files.createDirectories(pdfPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("创建文件夹时出错：" + e.getMessage());
                    return GraceJSONResult.ok("创建文件夹时出错：" + e.getMessage());
                }
            }

            // 将HTML转换为PDF并保存
            try {
                // 创建字体提供者并注册支持中文的字体
                FontProvider fontProvider = new FontProvider();
//                fontProvider.addSystemFonts(); // 使用系统字体

//                fontProvider.addFont(String.valueOf(new File("D:\\Project\\generateZipPdf\\SourceHanSerifCN-Regular.otf")));
//                fontProvider.addFont("http://60.205.114.119/yspg/SourceHanSerifCN-Regular.otf");

                String fontUrl = "http://dsd.nmgbigdata.com:1002/static/FangZhengFangSong.ttf";
                // 本地临时文件
                try {
                    Path tempFontFile = Files.createTempFile("temp-font", ".ttf");
                    // 下载字体文件
                    try (InputStream in = new URL(fontUrl).openStream();
                         FileOutputStream out = new FileOutputStream(tempFontFile.toFile())) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                    }

                    // 使用本地临时文件添加字体
                    fontProvider.addFont(tempFontFile.toFile().getAbsolutePath());

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


                HtmlConverter.convertToPdf(htmlContent, new FileOutputStream(pdfFileName), new ConverterProperties().setFontProvider(fontProvider));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }

            System.out.println("PDF created successfully: " + pdfFileName);
        }

        return GraceJSONResult.ok("报告已生成完毕！存放到D:/generateZipPdf文件夹");

    }


}
